package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.heima.common.constants.WemediaConstants.CANCEL_COLLECT_MATERIAL;
import static com.heima.common.constants.WemediaConstants.COLLECT_MATERIAL;

/**
 * @author JianKang
 * @create 2023-10-20 14:01
 */
@Service
@Transactional
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "无图片资源！");
        }
        //2.上传图片
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        String postFix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postFix, multipartFile.getInputStream());
            log.info("图片上传至minio中，fileId：{}", fileId);
        } catch (IOException e) {
            log.error("WmMaterialServiceImpl 图片上传失败！");
            throw new RuntimeException(e);
        }
        //3.图片url保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        // 0 是图片
        wmMaterial.setType((short) 0);
        // 0 是不收藏
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
//        log.debug("userId:{}", WmThreadLocalUtil.getUser().getApUserId());
        //检查登录
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.检查分页参数
        dto.checkParam();
        //3.分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        //4.是否收藏
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        Short isCollection = dto.getIsCollection();
        if (isCollection != null && isCollection == 1) {
            queryWrapper.eq(WmMaterial::getIsCollection, isCollection);
        }
        //5.按照用户查询
        queryWrapper.eq(WmMaterial::getUserId, user.getId());
        //6.结果降序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //7.分页
        page = page(page, queryWrapper);
        //8.查询列表
        long total = page.getTotal();
        List<WmMaterial> wmMaterialList = page.getRecords();
        //9.返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) total);
        pageResponseResult.setData(wmMaterialList);
        return pageResponseResult;
    }

    @Override
    public ResponseResult cancelCollect(Integer id) {
        //0.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.检查用户登录状态
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.获取用户id
        Integer userId = user.getId();
        //3.创建用户与收藏素材关联
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setUserId(userId);
        wmMaterial.setIsCollection(CANCEL_COLLECT_MATERIAL);
        //4.保存关联
        updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult collect(Integer id) {
        //0.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.检查用户登录状态
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.获取用户id
        Integer userId = user.getId();
        //3.创建用户与收藏素材关联
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setUserId(userId);
        wmMaterial.setIsCollection(COLLECT_MATERIAL);
        //4.保存关联
        updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        //0.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.检查用户登录状态
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.检查素材是否存在
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.检查图片关联信息
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        //3.1无关联删除
        if (count == 0) {
            boolean result = this.removeById(id);
            if (result) {
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件删除失败");
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
}
